﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using WMSABL;
using WMSABL.SY;
using WMSAML.SY;
using ElectronicWMSA.Comm.ClassFiles;
using ElectronicWMSA.Comm.Forms.Message;

namespace ElectronicWMSA.SY
{
    public partial class UserRGFrm : Form
    {
        #region
        private int _UserIDU = 0;
        private string strWhere = "";
        PublicDataSet bll_CommonPub = new PublicDataSet();
        TUsers_BLL bll_TUsers = new TUsers_BLL();
        TUsers_Entity entity = new TUsers_Entity();
        TUserRoleRelation_BLL bll_TUserRoleRelation = new TUserRoleRelation_BLL();
        public UserRGFrm()
        {
            InitializeComponent();
            this.strWhere = " EnableStatus=1 ";
            this.pageControlU.PageCurrent = 1;
            this.pageControlU.PageSize = 20;
            this.pageControlU.Bind();
            this.DBindRoles();
        }
        #endregion

        #region 数据分页
        private int DBindU()
        {
            ElectronicWMSA.Comm.Forms.MsControls.PageData pageData = new ElectronicWMSA.Comm.Forms.MsControls.PageData();
            pageData.TableName = "Vlh_TUserRM";
            pageData.PrimaryKey = "User_id";
            pageData.OrderStr = "User_id";
            pageData.PageIndex = this.pageControlU.PageCurrent;
            pageData.PageSize = this.pageControlU.PageSize;
            pageData.QueryCondition = strWhere;
            pageData.QueryFieldName = "*";

            this.pageControlU.bindingSource.DataSource = pageData.QueryDataTable().Tables[0];
            this.pageControlU.bindingNavigator.BindingSource = pageControlU.bindingSource;
            this.dataGridViewUserList.AutoGenerateColumns = false;
            this.dataGridViewUserList.DataSource = this.pageControlU.bindingSource;
            this.dataGridViewUserList.ClearSelection();
            this.dataGridViewUserList.CurrentCell = null;
            return pageData.TotalCount;
        }
        /// <summary>
        /// 控件事件
        /// </summary>
        private int pageControlU_EventPaging(ElectronicWMSA.Comm.Forms.MsControls.EventPagingArg e)
        {
            return DBindU();
        }
        #endregion

        #region 角色
        public void DBindRoles()
        {
            DataSet ds = new DataSet();
            ds = bll_CommonPub.GetDataSet("TRoles", "");
            DataTable dt = ds.Tables[0];
            DataRow dr = dt.NewRow();
            dr["Role_id"] = "0";
            dr["Role_name"] = "--请选择--";
            dt.Rows.InsertAt(dr, 0);
            this.comBoxURole.DataSource = dt;
            this.comBoxURole.ValueMember = "Role_id";
            this.comBoxURole.DisplayMember = "Role_name";
        }
        #endregion

        #region 查询
        private void btnUserSearch_Click(object sender, EventArgs e)
        {
            if (!SystemVariable.VaildationPermission("查询")) return;

            string roles = this.comBoxURole.Text.Trim();
            string name = this.txtUSearchName.Text.Trim();
            if (roles == "--请选择--") roles = "";
            if (radioButtonDisable.Checked == true)
            {
                strWhere = " EnableStatus=0 AND (Login_name LIKE '" + name + "%' OR Username LIKE '" + name + "%') AND Role_name LIKE '%" + roles + "%'";
            }
            if (radioButtonEnable.Checked == true)
            {
                strWhere = " EnableStatus=1 AND(Login_name LIKE '" + name + "%' OR Username LIKE '" + name + "%') AND Role_name LIKE '%" + roles + "%'";
            }
            if (radioButtonAll.Checked == true)
            {
                strWhere = " (Login_name LIKE '" + name + "%' OR Username LIKE '" + name + "%') AND Role_name LIKE '%" + roles + "%'";
            }
            this.btnUClear_Click(sender, e);
        }
        #endregion

        #region  新增、保存
        private void btnUSave_Click(object sender, EventArgs e)
        {
            if (btnUSave.Text == "添加")
                this.Add();
            else
                this.UpdateSave();
        }

        private void btnNewUser_Click(object sender, EventArgs e)
        {
            if (!SystemVariable.VaildationPermission("新增")) return;
            this.btnUSave.Text = "添加";
            this.tabAnalysisList.SelectedIndex = 1;
            this._UserIDU = 0;

            this.txtLoginName.Text = "";
            this.txtUserName.Text = "";
            this.txtPassWord1.Text = "";
            this.txtPassWord2.Text = "";
            this.txtMobile.Text = "";
            this.txtEmail.Text = "";
            this.txtLoginName.Enabled = true;
            this.txtPassWord1.Enabled = true;
            this.txtPassWord2.Enabled = true;

            this.txtLoginName.Focus();
        }

        #region 添加
        /// <summary>
        /// buffByte FileStream
        /// </summary>
        private byte[] buffByte = null;
        TUserRoleRelation_Entity entity_TUserRoleRelation = new TUserRoleRelation_Entity();
        TUserImag_BLL userImg_bll = new TUserImag_BLL();
        TUserImagEntity userEntity = new TUserImagEntity();

        public void Add()
        {
            if (!SystemVariable.VaildationPermission("新增")) return;

            #region 验证
            string loginName = this.txtLoginName.Text.Trim();
            if (loginName == "")
            {
                MessageClass.error("登录名不能为空!");
                this.txtLoginName.Focus();
                return;
            }
            if (bll_TUsers.ExistsByName(loginName))
            {
                MessageClass.error("登录名称已存在!");
                this.txtLoginName.Focus();
                return;
            }
            string userName = this.txtUserName.Text.Trim();
            if (userName == "")
            {
                MessageClass.error("请填写用户名!");
                this.txtUserName.Focus();
                return;
            }
            string password1 = this.txtPassWord1.Text.Trim();
            if (password1 == "")
            {
                MessageClass.error("用户密码不能为空!");
                this.txtPassWord1.Focus();
                return;
            }
            string password2 = this.txtPassWord2.Text.Trim();
            if (password2 == "")
            {
                MessageClass.error("确认密码不能为空!");
                this.txtPassWord2.Focus();
                return;
            }
            if (password1 != password2)
            {
                MessageClass.error("两次输入密码不一致!");
                this.txtPassWord1.Focus();
                return;
            }
            string mobile = this.txtMobile.Text.Trim();
            if (this.txtMobile.Text.Trim() != "")
            {
                if (!ValidationRegex.ValidatePhone(this.txtMobile.Text.Trim()))
                {
                    MessageClass.error("手机输入有误!");
                    this.txtMobile.Focus();
                    return;
                }
            }
            string email = this.txtEmail.Text.Trim();
            if (this.txtEmail.Text.Trim() != "")
            {
                if (!ValidationRegex.ValidateEmail(this.txtEmail.Text.Trim()))
                {
                    MessageClass.error("邮箱输入有误!");
                    this.txtEmail.Focus();
                    return;
                }
            }
            entity.Login_name = loginName;
            entity.Username = userName;
            if (organizationid == 0)
            {
                MessageClass.error("请选择所属部门!");
                return;
            }
            else
            {
                entity.Organization_id = organizationid;
            }
            entity.password = DesMd5.MD5Encrypt(password1);
            entity.Mobile = mobile;
            entity.Email = email;
            entity.Creat_time = DateTime.Now;
            entity.Login_time = DateTime.Now;
            entity.Last_login_time = DateTime.Now;
            if (radioButton1.Checked)
                entity.EnableStatus = 1;
            else
                entity.EnableStatus = 0;
            entity.LoginStatus = 0;
            #endregion


            if (MessageClass.enquire("确认添加信息！") == DialogResult.OK)
            {
                int result = bll_TUsers.Add_Users(entity);
                if (result > 0)
                {
                    entity = bll_TUsers.GetEntityByID(result);
                    if (entity != null)
                    {
                        //添加默认角色
                        entity_TUserRoleRelation.User_id = result;
                        entity_TUserRoleRelation.Role_id = 5;// 5 为员工角色表ID
                        bll_TUserRoleRelation.Add(entity_TUserRoleRelation);

                        if (_FileName != "")
                        {
                            FileStream fs = new FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                            buffByte = new byte[fs.Length];
                            fs.Read(buffByte, 0, (int)fs.Length);
                            fs.Close();
                            userEntity = new TUserImagEntity();
                            userEntity.UserID = _UserIDU;
                            userEntity.Img = buffByte;
                            userEntity.AddTime = DateTime.Now;

                            userImg_bll.Add(userEntity);
                        }
                    }

                    SystemVariable.AddLogInfo("用户管理", "添加了新用户 【" + entity.Username + "】");

                    MessageClass.right("添加成功！");
                    strWhere = " EnableStatus=1 ";
                    this._UserIDU = 0;
                    this.tabAnalysisList.SelectedIndex = 0;
                    this.pageControlU.Bind();
                    this._FileName = "";
                    this.pictureBoxMImage.Image = global::ElectronicWMSA.Properties.Resources.默认图片;
                }
                else
                {
                    MessageClass.error("添加失败!");
                }
            }
        }
        #endregion

        #region 修改
        private void UpdateSave()
        {
            if (!SystemVariable.VaildationPermission("编辑")) return;
            if (_UserIDU > 0)
            {
                entity = bll_TUsers.GetEntityByID(_UserIDU);
                if (entity == null)
                {
                    MessageClass.error("请选择信息！");
                    return;
                }
                #region 验证
                string userName = this.txtUserName.Text.Trim();
                if (userName == "")
                {
                    MessageClass.error("请填写用户名！");
                    this.txtUserName.Focus();
                    return;
                }
                string mobile = this.txtMobile.Text.Trim();
                if (this.txtMobile.Text.Trim() != "")
                {
                    if (!ValidationRegex.ValidatePhone(this.txtMobile.Text.Trim()))
                    {
                        MessageClass.error("手机输入有误!");
                        this.txtMobile.Focus();
                        return;
                    }
                }
                string email = this.txtEmail.Text.Trim();
                if (this.txtEmail.Text.Trim() != "")
                {
                    if (!ValidationRegex.ValidateEmail(this.txtEmail.Text.Trim()))
                    {
                        MessageClass.error("邮箱输入有误!");
                        this.txtEmail.Focus();
                        return;
                    }
                }
                if (organizationid == 0)
                {
                    MessageClass.error("请选择所属部门!");
                    return;
                }
                else
                {
                    entity.Organization_id = organizationid;
                }
                entity.Username = userName;
                entity.Mobile = mobile;
                entity.Email = email;
                if (radioButton1.Checked)
                    entity.EnableStatus = 1;
                else
                    entity.EnableStatus = 0;
                entity.LoginStatus = 0;
                #endregion

                if (MessageClass.enquire("确认修改信息！") == DialogResult.OK)
                {
                    if (bll_TUsers.Update(entity))
                    {
                        if (_FileName != "")
                        {
                            userEntity = new TUserImagEntity();
                            userEntity = userImg_bll.GetEntityByUID(_UserIDU);
                            if (userEntity != null)
                            {
                                FileStream fs = new FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                                buffByte = new byte[fs.Length];
                                fs.Read(buffByte, 0, (int)fs.Length);
                                fs.Close();

                                userEntity.Img = buffByte;
                                userImg_bll.Update(userEntity);
                            }
                            else
                            {
                                FileStream fs = new FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                                buffByte = new byte[fs.Length];
                                fs.Read(buffByte, 0, (int)fs.Length);
                                fs.Close();

                                userEntity = new TUserImagEntity();
                                userEntity.UserID = _UserIDU;
                                userEntity.Img = buffByte;
                                userEntity.AddTime = DateTime.Now;
                                userImg_bll.Add(userEntity);
                            }
                        }

                        SystemVariable.AddLogInfo("用户管理", "修改用户  【" + entity.Username + "】。");

                        MessageClass.right("修改成功！");

                        this.btnUSave.Text = "添加";
                        this._UserIDU = 0;
                        this.pageControlU.Bind();
                        this.tabAnalysisList.SelectedIndex = 0;
                        this._FileName = "";
                        this.pictureBoxMImage.Image = global::ElectronicWMSA.Properties.Resources.默认图片;
                    }
                    else
                    {
                        MessageClass.error("失败!");
                    }
                }
            }
        }
        #endregion

        #endregion

        #region 取消
        private void btnUClear_Click(object sender, EventArgs e)
        {
            this._UserIDU = 0;
            this.txtLoginName.Text = "";
            this.txtUserName.Text = "";
            this.txtPassWord1.Text = "";
            this.txtPassWord2.Text = "";
            this.txtMobile.Text = "";
            this.txtEmail.Text = "";
            this.txtLoginName.Enabled = true;
            this.txtPassWord1.Enabled = true;
            this.txtPassWord2.Enabled = true;
            this.pageControlU.Bind();
        }
        #endregion

        #region 序号
        private void dataGridViewUserList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            SolidBrush b = new SolidBrush(dataGridViewUserList.RowHeadersDefaultCellStyle.ForeColor);
            e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), dataGridViewUserList.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
        }

        /// <summary>
        /// 显示全部用户
        /// </summary> 
        private void radioButtonAll_CheckedChanged(object sender, EventArgs e)
        {
            strWhere = "";
            this.btnUClear_Click(sender, e);
        }

        /// <summary>
        /// 显示启用用户
        /// </summary> 
        private void radioButtonEnable_CheckedChanged(object sender, EventArgs e)
        {
            strWhere = " EnableStatus=1 ";
            this.btnUClear_Click(sender, e);
        }

        /// <summary>
        /// 显示禁用用户
        /// </summary> 
        private void radioButtonDisable_CheckedChanged(object sender, EventArgs e)
        {
            strWhere = " EnableStatus=0 ";
            this.btnUClear_Click(sender, e);
        }
        #endregion

        #region 事件
        private void dataGridViewUserList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                if (this.dataGridViewUserList.Rows.Count != 0)
                {
                    #region 获取单列详细信息
                    if (e.ColumnIndex != -1 && this.dataGridViewUserList.CurrentCell.ColumnIndex == 0)
                    {
                        this._UserIDU = Convert.ToInt32(this.dataGridViewUserList.CurrentRow.Cells["User_id"].Value.ToString());
                        if (_UserIDU > 0)
                        {
                            if (_UserIDU == 2)
                            {
                                MessageClass.error("该用户不能修改！");
                                return;
                            }
                            this.tabAnalysisList.SelectedIndex = 1;
                            userEntity = new TUserImagEntity();
                            userEntity = userImg_bll.GetEntityByUID(_UserIDU);
                            if (userEntity != null)
                            {
                                MemoryStream ms = new MemoryStream(userEntity.Img);
                                this.pictureBoxMImage.Image = Bitmap.FromStream(ms, true);
                            }
                            else
                            {
                                this.pictureBoxMImage.Image = global::ElectronicWMSA.Properties.Resources.默认图片;
                            }
                            Vlh_TUserRM_Entity entity = new Vlh_TUserRM_Entity();
                            entity = bll_TUsers.GetEntityVByID(_UserIDU);
                            if (entity == null) return;

                            this.txtDeptName.Text = bll_TOrganization.GetEntityByID(entity.Organization_id).Organization_name;
                            this.organizationid = entity.Organization_id;
                            this.txtLoginName.Text = entity.Login_name;
                            this.txtUserName.Text = entity.Username;
                            this.txtPassWord1.Text = "******";
                            this.txtPassWord2.Text = "******";
                            this.txtMobile.Text = entity.Mobile;
                            this.txtEmail.Text = entity.Email;
                            if (entity.EnableStatus == 1)
                            {
                                this.radioButton1.Checked = true;
                                this.radioButton0.Checked = false;
                            }
                            else
                            {
                                this.radioButton1.Checked = false;
                                this.radioButton0.Checked = true;
                            }
                            this.txtLoginName.Enabled = false;
                            this.txtPassWord1.Enabled = false;
                            this.txtPassWord2.Enabled = false;

                            this.btnUSave.Text = "修改";
                        }
                    }
                    else
                    {
                        this._UserIDU = 0;
                        this.txtLoginName.Text = "";
                        this.txtUserName.Text = "";
                        this.txtPassWord1.Text = "";
                        this.txtPassWord2.Text = "";
                        this.txtMobile.Text = "";
                        this.txtEmail.Text = "";
                        this.txtLoginName.Enabled = true;
                        this.txtPassWord1.Enabled = true;
                        this.txtPassWord2.Enabled = true;
                    }
                    #endregion

                    #region 确认删除
                    if (e.ColumnIndex != -1 && this.dataGridViewUserList.CurrentCell.ColumnIndex == 1)
                    {
                        if (!SystemVariable.VaildationPermission("删除")) return;
                        this._UserIDU = Convert.ToInt32(dataGridViewUserList.CurrentRow.Cells["User_id"].Value.ToString());
                        if (_UserIDU == 0)
                        {
                            MessageClass.error("请选择信息！");
                            return;
                        }
                        if (_UserIDU == 2)
                        {
                            MessageClass.warning("该用户不能被删除！");
                            return;
                        }
                        if (MessageClass.enquire("删除用户！") == DialogResult.OK)
                        {
                            if (bll_TUsers.Delete(_UserIDU))
                            {
                                entity = new TUsers_Entity();
                                entity = bll_TUsers.GetEntityByID(_UserIDU);
                                if (entity != null)
                                {
                                    SystemVariable.AddLogInfo("用户管理", "注销用户  【" + entity.Username + "】信息。");
                                }
                                MessageClass.right("成功！");
                                this._UserIDU = 0;
                                this.dataGridViewUserList.Rows.RemoveAt(e.RowIndex);
                            }
                            else
                            {
                               MessageClass.warning("失败！");
                            }
                        }
                    }
                    #endregion
                }
            }
        }
        #endregion


        #region 退出
        private void linkLabelClose_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPages();
        }

        private void linkLabellinkLabelCloseAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseAllTabPages();
        }

        private void linkLabelCloseElse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPageElse();
        }
        #endregion

        #region 返回列表
        private void btnRetunList_Click(object sender, EventArgs e)
        {
            this.tabAnalysisList.SelectedIndex = 0;
        }
        #endregion

        public int organizationid = 0;
        TOrganization_Entity entity_TOrganization = new TOrganization_Entity();
        TOrganization_BLL bll_TOrganization = new TOrganization_BLL();
        private void btnSelectDept_Click(object sender, EventArgs e)
        {
            ElectronicWMSA.SY.ListFrm.OrganizationListFrm frm = new ElectronicWMSA.SY.ListFrm.OrganizationListFrm();
            frm.ShowDialog();
            organizationid = frm.Organization_id;
            if (organizationid > 0)
            {
                entity_TOrganization = bll_TOrganization.GetEntityByID(organizationid);
                if (entity_TOrganization != null)
                {
                    this.txtDeptName.Text = entity_TOrganization.Organization_name;
                }
            }
            else
            {
                this.txtDeptName.Text = "";
            }
        }

        private void btnUpdatePWD_Click(object sender, EventArgs e)
        {
            InitialPasswordFrm frm = new InitialPasswordFrm();
            frm.ShowDialog();
        }
        /// <summary>
        /// pht Name
        /// </summary>
        private string _FileName = "";
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                _FileName = ofd.FileName;
                FileStream fs = new FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] buffByte1 = new byte[fs.Length];
                fs.Read(buffByte1, 0, (int)fs.Length);
                fs.Close();
                MemoryStream ms = new MemoryStream(buffByte1);
                Image image = Image.FromStream(ms, true);
                this.pictureBoxMImage.Image = image;
            }
        }
    }
}
